import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import '../../resources/kq_theme_colors.dart';
import 'package:kq_flutter_widgets/widgets/selectTag/select_tag_presets.dart';
import 'package:kq_flutter_widgets/widgets/selectTag/select_tag_presets_util.dart';


/// 选择切换的长条(均分|滚动|换行) @author 高裕
class KqSelectTag extends StatefulWidget {
  final List<String> tagList;

  /// 选择tag的回调,返回选中 tag 的位置
  final void Function(int index)? onSelect;

  /// tag的默认选中值
  final int initPosition;

  /// 是否默认选中
  final bool initChoose;

  /// 布局模式
  final KqSelectTagMode mode;

  /// 背景高度
  final double? bgHeight;

  /// 背景颜色
  final Color? bgColor;

  /// 背景padding
  final EdgeInsetsGeometry? bgPadding;

  /// 文本大小
  final double? textSize;

  /// 文本选中颜色
  final Color? textSelectColor;

  /// 文本普通颜色
  final Color? textNormalColor;

  /// 文本最大行数
  final int? textMaxLine;

  /// 文本Overflow
  final TextOverflow? textOverflow;

  /// 文本样式
  final TextStyle? Function(int index)? textStyle;

  /// 自定义子项Decoration
  final Decoration? Function(int index)? itemDecoration;

  /// 子项大小限制
  final BoxConstraints? itemConstraints;

  /// 子项圆角
  final BorderRadiusGeometry? radius;

  /// 子项padding
  final EdgeInsetsGeometry? itemPadding;

  /// 子项margin
  final EdgeInsetsGeometry? itemMargin;

  /// 子项宽度
  final double? itemWidth;

  /// 子项高度
  final double? itemHeight;

  /// 子项选中颜色
  final Color? itemSelectColor;

  /// 子项普通颜色
  final Color? itemNormalColor;

  /// 子项边框
  final BoxBorder? Function(int index)? itemBoxBorder;

  /// warp的属性(主轴间距)
  final double? spacing;

  /// warp的属性(交叉轴间距)
  final double? runSpacing;

  /// warp的属性(主轴对齐方式)
  final WrapAlignment? wrapAlignment;

  /// warp的属性(叉轴对齐方式)
  final WrapCrossAlignment? wrapCrossAlignment;

  /// warp的属性(主轴垂直方向每一行的对齐方式)
  final WrapAlignment? wrapRunAlignment;

  /// 自定义布局(不可以单独使用，必须要有CustomItem，不受模式影响)
  final CustomLayout? customLayout;

  /// 自定义item(可单独使用)
  final CustomItem? customItem;

  /// 何时切换成滚动模式
  final WhenToScroll? whenToScroll;

  /// 预设
  final SelectTagPresets? presets;

  /// 获取state,用于直接修改position等操作
  final Function(KqSelectTagState state)? getState;

  const KqSelectTag({
    Key? key,
    required this.tagList,
    this.onSelect,
    this.initChoose = true,
    this.initPosition = 0,
    this.mode = KqSelectTagMode.smart,
    this.bgColor,
    this.textSize,
    this.textStyle,
    this.textMaxLine,
    this.textOverflow,
    this.itemDecoration,
    this.itemConstraints,
    this.radius,
    this.itemPadding,
    this.itemMargin,
    this.bgPadding,
    this.bgHeight,
    this.itemWidth,
    this.itemHeight,
    this.textSelectColor,
    this.textNormalColor,
    this.itemSelectColor,
    this.itemNormalColor,
    this.itemBoxBorder,
    this.spacing,
    this.runSpacing,
    this.wrapAlignment,
    this.wrapCrossAlignment,
    this.wrapRunAlignment,
    this.customLayout,
    this.customItem,
    this.whenToScroll,
    this.presets,
    this.getState,
  }) : super(key: key);

  /// 文本模式，没背景，有预设
  const KqSelectTag.text({
    Key? key,
    required this.tagList,
    this.onSelect,
    this.initChoose = true,
    this.initPosition = 0,
    this.mode = KqSelectTagMode.scroll,
    this.bgColor,
    this.textSize,
    this.textStyle,
    this.textMaxLine,
    this.textOverflow,
    this.itemDecoration,
    this.itemConstraints,
    this.radius,
    this.itemPadding,
    this.itemMargin,
    this.bgPadding,
    this.bgHeight,
    this.itemWidth,
    this.itemHeight,
    this.textSelectColor = KqThemeColors.text26,
    this.textNormalColor = KqThemeColors.text8C,
    this.itemSelectColor = KqThemeColors.bgTransparent,
    this.itemNormalColor = KqThemeColors.bgTransparent,
    this.itemBoxBorder,
    this.spacing,
    this.runSpacing,
    this.wrapAlignment,
    this.wrapCrossAlignment,
    this.wrapRunAlignment,
    this.customLayout,
    this.customItem,
    this.whenToScroll,
    this.presets = SelectTagPresets.textLeftScroll,
    this.getState,
  }) : super(key: key);

  @override
  State<KqSelectTag> createState() => KqSelectTagState();
}

class KqSelectTagState extends State<KqSelectTag> {
  int? position;

  List<Widget> tagLayoutList = [];

  SelectTagPresetsEntity? entity;

  @override
  void initState() {
    super.initState();
    widget.getState?.call(this);
    if (widget.initChoose && position == null) {
      position = widget.initPosition;
    }
  }

  @override
  void didUpdateWidget(covariant KqSelectTag oldWidget) {
    super.didUpdateWidget(oldWidget);
    widget.getState?.call(this);
  }

  @override
  Widget build(BuildContext context) {
    tagLayoutList = [];
    entity = SelectTagPresetsUtil.presets(widget, this,
        widget.presets != null ? widget.presets! : SelectTagPresets.normal);
    for (int i = 0; i < widget.tagList.length; i++) {
      tagLayoutList.add(_chooseItem(i));
    }
    return _chooseLayout();
  }

  Widget _chooseLayout() {
    if (widget.customLayout != null) {
      return _customLayout();
    }
    switch (widget.mode) {
      case KqSelectTagMode.share:
        return _shareLayout();
      case KqSelectTagMode.scroll:
        return _scrollLayout();
      case KqSelectTagMode.wrap:
        return _warpLayout();
      case KqSelectTagMode.smart:
        if (changeToScroll()) {
          return _scrollLayout();
        } else {
          return _shareLayout();
        }
    }
  }

  Widget _chooseItem(int i) {
    if (widget.customItem != null) {
      return _customItem(i);
    }
    switch (widget.mode) {
      case KqSelectTagMode.share:
        return _shareItem(i);
      case KqSelectTagMode.scroll:
        return _scrollItem(i);
      case KqSelectTagMode.wrap:
        return _warpItem(i);
      case KqSelectTagMode.smart:
        if (changeToScroll()) {
          return _scrollItem(i);
        } else {
          return _shareItem(i);
        }
    }
  }

  /// 均分布局
  Widget _shareLayout() {
    return Container(
      height: widget.bgHeight,
      padding: widget.bgPadding ?? entity?.bgPadding,
      color: widget.bgColor ?? KqThemeColors.bgWhite,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: tagLayoutList,
      ),
    );
  }

  /// 均分项
  Widget _shareItem(int i) {
    return Expanded(
        flex: 1,
        child: GestureDetector(
          onTap: () {
            setState(() {
              position = i;
            });
            if (widget.onSelect != null) {
              widget.onSelect!(i);
            }
          },
          child: Container(
            alignment: Alignment.center,
            child: Container(
              width: widget.itemWidth,
              height: widget.itemHeight,
              constraints: widget.itemConstraints,
              decoration: widget.itemDecoration != null
                  ? widget.itemDecoration!(i)
                  : BoxDecoration(
                      color: position != null && position == i
                          ? widget.itemSelectColor ??
                              KqThemeColors.textLightBlue
                          : widget.itemNormalColor ?? KqThemeColors.textWhite,
                      borderRadius: widget.radius ??
                          BorderRadius.all(Radius.circular(15.r)),
                      border: widget.itemBoxBorder != null
                          ? widget.itemBoxBorder!(i)
                          : null),
              // 智能模式下均分不使用这个属性
              margin: widget.mode == KqSelectTagMode.smart
                  ? null
                  : widget.itemMargin,
              padding: widget.itemPadding ?? entity?.itemPadding,
              child: Text(
                widget.tagList[i],
                style: widget.textStyle != null
                    ? widget.textStyle!(i)
                    : TextStyle(
                        fontSize: widget.textSize ?? entity?.textSize,
                        color: position != null && position == i
                            ? widget.textSelectColor ?? KqThemeColors.textWhite
                            : widget.textNormalColor ?? KqThemeColors.text26),
                textAlign: TextAlign.center,
                maxLines: widget.textMaxLine ?? 1,
                overflow: widget.textOverflow,
              ),
            ),
          ),
        ));
  }

  /// 滑动布局
  Widget _scrollLayout() {
    return Container(
      width: double.infinity,
      height: widget.bgHeight ?? entity?.bgHeight,
      color: widget.bgColor ?? KqThemeColors.bgWhite,
      padding: widget.bgPadding ?? entity?.bgPadding,
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: tagLayoutList,
      ),
    );
  }

  /// 滑动项
  Widget _scrollItem(int i) {
    return GestureDetector(
        onTap: () {
          setState(() {
            position = i;
          });
          if (widget.onSelect != null) {
            widget.onSelect!(i);
          }
        },
        child: Container(
          alignment: Alignment.center,
          child: Container(
            width: widget.itemWidth,
            height: widget.itemHeight,
            constraints: widget.itemConstraints,
            decoration: widget.itemDecoration != null
                ? widget.itemDecoration!(i)
                : BoxDecoration(
                    color: position != null && position == i
                        ? widget.itemSelectColor ?? KqThemeColors.textLightBlue
                        : widget.itemNormalColor ?? KqThemeColors.textWhite,
                    borderRadius: widget.radius ??
                        BorderRadius.all(Radius.circular(15.r)),
                    border: widget.itemBoxBorder != null
                        ? widget.itemBoxBorder!(i)
                        : null),
            margin: widget.itemMargin ?? entity?.itemMargin,
            padding: widget.itemPadding ?? entity?.itemPadding,
            child: Text(
              widget.tagList[i],
              style: widget.textStyle != null
                  ? widget.textStyle!(i)
                  : TextStyle(
                      fontSize: widget.textSize ?? entity?.textSize,
                      color: position != null && position == i
                          ? widget.textSelectColor ?? KqThemeColors.textWhite
                          : widget.textNormalColor ?? KqThemeColors.text26),
              textAlign: TextAlign.center,
              maxLines: widget.textMaxLine ?? 1,
              overflow: widget.textOverflow,
            ),
          ),
        ));
  }

  /// 换行布局
  Widget _warpLayout() {
    return Container(
      width: double.infinity,
      height: widget.bgHeight,
      color: widget.bgColor ?? KqThemeColors.bgWhite,
      padding: widget.bgPadding ?? entity?.bgPadding,
      child: Wrap(
        alignment: widget.wrapAlignment ?? WrapAlignment.spaceEvenly,
        crossAxisAlignment:
            widget.wrapCrossAlignment ?? WrapCrossAlignment.center,
        runAlignment: widget.wrapRunAlignment ?? WrapAlignment.start,
        spacing: widget.spacing ?? 0,
        runSpacing: widget.runSpacing ?? 10.r,
        children: tagLayoutList,
      ),
    );
  }

  /// 换行项
  Widget _warpItem(int i) {
    return GestureDetector(
        onTap: () {
          setState(() {
            position = i;
          });
          if (widget.onSelect != null) {
            widget.onSelect!(i);
          }
        },
        child: Container(
          width: widget.itemWidth,
          height: widget.itemHeight,
          // warp子项在没宽度时，设置alignment子项会无限宽
          alignment: (widget.itemWidth != null) ? Alignment.center : null,
          constraints: widget.itemConstraints,
          decoration: widget.itemDecoration != null
              ? widget.itemDecoration!(i)
              : BoxDecoration(
                  color: position != null && position == i
                      ? widget.itemSelectColor ?? KqThemeColors.textLightBlue
                      : widget.itemNormalColor ?? KqThemeColors.textWhite,
                  borderRadius:
                      widget.radius ?? BorderRadius.all(Radius.circular(15.r)),
                  border: widget.itemBoxBorder != null
                      ? widget.itemBoxBorder!(i)
                      : null),
          margin: widget.itemMargin ?? entity?.itemMargin,
          padding: widget.itemPadding ?? entity?.itemPadding,
          child: Text(
            widget.tagList[i],
            style: widget.textStyle != null
                ? widget.textStyle!(i)
                : TextStyle(
                    fontSize: widget.textSize ?? entity?.textSize,
                    color: position != null && position == i
                        ? widget.textSelectColor ?? KqThemeColors.textWhite
                        : widget.textNormalColor ?? KqThemeColors.text26),
            textAlign: TextAlign.center,
            maxLines: widget.textMaxLine ?? 1,
            overflow: widget.textOverflow,
          ),
        ));
  }

  /// 自定义布局
  Widget _customLayout() {
    if (widget.customLayout != null) {
      return widget.customLayout!();
    }
    return Container();
  }

  /// 自定义项
  Widget _customItem(int i) {
    if (widget.customItem != null) {
      if ((widget.mode == KqSelectTagMode.share ||
              (widget.mode == KqSelectTagMode.smart && !changeToScroll())) &&
          widget.customLayout == null) {
        return Expanded(
            child: GestureDetector(
                onTap: () {
                  setState(() {
                    position = i;
                  });
                  if (widget.onSelect != null) {
                    widget.onSelect!(i);
                  }
                },
                child: widget.customItem!(i, position, widget.tagList[i])));
      } else {
        return GestureDetector(
            onTap: () {
              setState(() {
                position = i;
              });
              if (widget.onSelect != null) {
                widget.onSelect!(i);
              }
            },
            child: widget.customItem!(i, position, widget.tagList[i]));
      }
    }
    return Container();
  }

  /// 智能模式控制
  bool changeToScroll() {
    if (widget.whenToScroll != null) {
      return widget.whenToScroll!(widget.tagList);
    }
    double maxWidth = paintWidthWithTextStyle("十六个中文的宽度是多少呢你猜你猜");
    double width = 0;
    for (String s in widget.tagList) {
      width = width + paintWidthWithTextStyle(s);
    }
    if (width > maxWidth) {
      return true;
    }
    return false;
  }

  /// 计算文本宽度
  double paintWidthWithTextStyle(
    String text,
  ) {
    final TextPainter textPainter = TextPainter(
        text: TextSpan(
            text: text,
            style: TextStyle(fontSize: widget.textSize ?? entity?.textSize)),
        maxLines: 1,
        textDirection: TextDirection.ltr)
      ..layout(minWidth: 0, maxWidth: double.infinity);
    return textPainter.size.width;
  }
}

/// 布局模式
enum KqSelectTagMode {
  /// 均分 (超过4项，按UI规范，不建议使用，平时用的都用智能模式，兼容多语言)
  share,

  /// 滚动 (有时用这个)
  scroll,

  /// 换行 (一般用不到)
  wrap,

  /// 智能切换均分和滚动 (一般用这个)
  smart,
}

/// 自定义布局
typedef CustomLayout = Widget Function();

/// 自定义item
typedef CustomItem = Widget Function(
    int position, int? selectPosition, String text);

/// 何时切换成滚动模式
typedef WhenToScroll = bool Function(List<String> list);
